package com.northking.statisticsdemo.circleQueue;

import cn.hutool.core.io.FileUtil;
import org.reflections.Reflections;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 动态加载外部JAR包公共基础类
 * @author: alienware
 * @date: 2021年11月06日 0:09
 */
public class DynamicLoadBusinessJar {
    private static final String CHAIN_BUSINESS_DIR = "E:\\coderHelp\\StatisticsDemo\\";
    private static final String CHAIN_PKG_PATH = "com.northking.chainResponsibility";
    protected Reflections reflections;

    public DynamicLoadBusinessJar() {
    }

    protected void initJarPath() {
        List<URLClassLoader> urlClassLoaderList = new ArrayList<>();
        URLClassLoader baseClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
        getAllClassLoader(urlClassLoaderList, baseClassLoader);
        try {
            Method addUrlMethod = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            if (!addUrlMethod.isAccessible()) {
                addUrlMethod.setAccessible(true);
            }
            // TODO 这里只做了Jar的增加没有做Jar的减少 这里会导致真正业务逻辑找不到的bug，所以目前需测试只做新增jar后续修改一下
            for (String fileName : FileUtil.listFileNames(CHAIN_BUSINESS_DIR)) {
                File jarFile = FileUtil.file(CHAIN_BUSINESS_DIR + fileName);
                for (URLClassLoader urlClassLoader: urlClassLoaderList){
                    addUrlMethod.invoke(urlClassLoader, jarFile.toURI().toURL());
                }
            }
        } catch (NoSuchMethodException | MalformedURLException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }

        reflections = new Reflections(CHAIN_PKG_PATH);
        System.out.println("a");
    }

    private void getAllClassLoader(List<URLClassLoader> urlClassLoaderList, URLClassLoader baseClassLoader) {
        if (null != baseClassLoader) {
            urlClassLoaderList.add(baseClassLoader);
            getAllClassLoader(urlClassLoaderList, (URLClassLoader) baseClassLoader.getParent());
        }
    }
}
